﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
using RotovapPlatform.Application.Services.Devices;
using RotovapPlatform.Domain.Equipment.Device.Robot.Dto;
using System.Collections.ObjectModel;
using RotovapPlatform.Domain.Equipment.Device.Robot.Enums;
using RotovapPlatform.Domain.Equipment.Interfaces.Services;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;

namespace RotovapPlatform.UI.ViewModels.DeviceMaintenance.ManualOperation
{
	/// <summary>
	/// 机器人控制视图模型
	/// </summary>
	public partial class RobotControlViewModel : ObservableObject, IDisposable
	{
		private readonly IDeviceManager _deviceManager;
		private readonly IDeviceStatusService _deviceStatusService;
		private readonly ILogger<RobotControlViewModel> _logger;
		private bool _disposed;

		/// <summary>
		/// 构造函数
		/// </summary>
		public RobotControlViewModel(
			IDeviceManager deviceManager,
			IDeviceStatusService deviceStatusService,
			ILogger<RobotControlViewModel> logger)
		{
			_deviceManager = deviceManager;
			_deviceStatusService = deviceStatusService;
			_logger = logger;

			// 初始化任务参数
			InitializeTaskParameters();

			// 订阅设备状态变化事件
			//_deviceStatusService.DeviceStatusChanged += OnDeviceStatusChanged;
			_logger?.LogInformation("已订阅设备状态变化事件");

			// 立即刷新一次状态
			_ = RefreshStatus();
		}

		#region 可观察属性
		// 机器人状态
		[ObservableProperty]
		private RobotStatusDto _robotStatus = new();

		// 任务反馈
		[ObservableProperty]
		private RobotTaskFeedBackDto _taskFeedback = new();

		// 当前任务参数
		[ObservableProperty]
		private RobotTaskSendDto _currentTask = new();

		// 工艺状态文本
		[ObservableProperty]
		private string _processStateText = "未知";

		// 抓手状态文本
		[ObservableProperty]
		private string _gripperStateText = "未知";

		// 任务完成状态文本
		[ObservableProperty]
		private string _taskFinishStateText = "未知";

		// 是否连接
		[ObservableProperty]
		private bool _isConnected;

		// 执行结果
		[ObservableProperty]
		private string _executionResult = "准备就绪";

		// 是否正在加载
		[ObservableProperty]
		private bool _isLoading;
		#endregion

		#region 控制命令
		/// <summary>
		/// 上电命令
		/// </summary>
		[RelayCommand]
		private async Task PowerOn()
		{
			await ExecuteWithFeedback(
				"上电",
				async () => await SendControlCommand(cmd => cmd.StartProgram = true)
			);
		}

		/// <summary>
		/// 使能命令
		/// </summary>
		[RelayCommand]
		private async Task Enable()
		{
			await ExecuteWithFeedback(
				"使能",
				async () => await SendControlCommand(cmd => cmd.Enable = true)
			);
		}

		/// <summary>
		/// 急停命令
		/// </summary>
		[RelayCommand]
		private async Task Stop()
		{
			await ExecuteWithFeedback(
				"急停",
				async () => await SendControlCommand(cmd => cmd.ProtectiveStop = true)
			);
		}

		/// <summary>
		/// 暂停命令
		/// </summary>
		[RelayCommand]
		private async Task Pause()
		{
			await ExecuteWithFeedback(
				"暂停",
				async () => await SendControlCommand(cmd => cmd.PauseProgram = true)
			);
		}

		/// <summary>
		/// 继续命令
		/// </summary>
		[RelayCommand]
		private async Task Continue()
		{
			await ExecuteWithFeedback(
				"继续",
				async () => await SendControlCommand(cmd => cmd.ContinueProgram = true)
			);
		}

		/// <summary>
		/// 清除错误命令
		/// </summary>
		[RelayCommand]
		private async Task ClearError()
		{
			await ExecuteWithFeedback(
				"清除错误",
				async () => await SendControlCommand(cmd => cmd.ClearError = true)
			);
		}

		/// <summary>
		/// 重置命令
		/// </summary>
		[RelayCommand]
		private async Task Reset()
		{
			CurrentTask.TaskType = TaskType.MoveToHome;
			await SendTask();
		}

		/// <summary>
		/// 发送任务命令
		/// </summary>
		[RelayCommand]
		private async Task SendTask()
		{
			await ExecuteWithFeedback("发送任务", async () =>
			{
				if (_deviceManager.Robot != null && CurrentTask != null)
				{
					// 设置任务参数
					var paramResult = await _deviceManager.Robot.SetTaskParametersAsync(CurrentTask);
					if (!paramResult.Success)
					{
						throw new Exception($"设置任务参数失败: {paramResult.Message}");
					}

					// 启动任务
					var result = await _deviceManager.Robot.StartAsync(1);
					if (!result.Success)
					{
						throw new Exception($"任务启动失败: {result.Message}");
					}

					return "任务启动成功";
				}

				throw new Exception("机器人未初始化或任务参数为空");
			});
		}

		/// <summary>
		/// 刷新状态命令
		/// </summary>
		[RelayCommand]
		private async Task RefreshStatus()
		{
			if (_disposed)
				return;

			try
			{
				IsLoading = true;
				ExecutionResult = "正在刷新状态...";

				if (_deviceManager?.Robot == null)
				{
					ExecutionResult = "设备未初始化，无法刷新状态";
					IsConnected = false;
					return;
				}

				var (taskFeedback, deviceStatus) = await _deviceManager.Robot.GetStatusAsync();

				// 使用UI线程调度器更新状态
				//		App.Current.Dispatcher.Invoke(() =>
				//	{
				// 更新状态
				RobotStatus = deviceStatus;
				TaskFeedback = taskFeedback;

				// 更新连接状态
				IsConnected = deviceStatus != null && TaskFeedback != null &&
							  TaskFeedback.RobotProcessState != RobotProcessState.Disconnected;

				// 更新状态显示文本
				UpdateStatusText();
				//		});

				if (!IsConnected)
				{
					ExecutionResult = "机器人已断开连接，正在尝试重连...";
					_logger.LogWarning("机器人已断开连接，正在尝试重连");
				}
				else
				{
					ExecutionResult = "状态刷新成功";
					_logger.LogDebug("机器人状态刷新成功"); // 降级日志级别，减少日志量
				}
			}
			catch (Exception ex)
			{
				ExecutionResult = $"状态刷新失败: {ex.Message}";
				IsConnected = false;
				_logger.LogError(ex, "刷新机器人状态失败");
			}
			finally
			{
				IsLoading = false;
			}
		}
		#endregion

		#region 私有方法
		/// <summary>
		/// 初始化任务参数
		/// </summary>
		private void InitializeTaskParameters()
		{
			CurrentTask = new RobotTaskSendDto
			{
				TaskType = TaskType.None,
				BottleType = 1,
				Position = 1,
				NeedScan = 0
			};
		}

		/// <summary>
		/// 发送控制命令
		/// </summary>
		private async Task<string> SendControlCommand(Action<RobotControlCommandDto> configureCommand)
		{
			if (_deviceManager.Robot == null)
			{
				throw new Exception("机器人未初始化");
			}

			var command = new RobotControlCommandDto();
			configureCommand(command);

			var result = await _deviceManager.Robot.SendControlCommandAsync(command);
			if (!result.Success)
			{
				throw new Exception($"命令发送失败: {result.Message}");
			}

			return $"命令发送成功";
		}

		/// <summary>
		/// 执行操作并处理反馈
		/// </summary>
		private async Task ExecuteWithFeedback(string actionName, Func<Task<string>> action)
		{
			if (_disposed)
				return;

			try
			{
				IsLoading = true;
				ExecutionResult = $"正在执行{actionName}操作...";

				var result = await action();
				ExecutionResult = result;

				// 执行成功后刷新状态
				await RefreshStatus();
			}
			catch (Exception ex)
			{
				ExecutionResult = $"{actionName}失败: {ex.Message}";
				_logger.LogError(ex, $"{actionName}操作失败");
			}
			finally
			{
				IsLoading = false;
			}
		}

		/// <summary>
		/// 更新状态显示文本
		/// </summary>
		private void UpdateStatusText()
		{
			// 更新处理状态文本
			ProcessStateText = TaskFeedback?.RobotProcessState switch
			{
				RobotProcessState.Idle => "待机",
				RobotProcessState.InTask => "工作中",
				RobotProcessState.Error => "错误",
				RobotProcessState.Disconnected => "已断开",
				_ => "未知"
			};

			// 更新抓手状态文本
			GripperStateText = TaskFeedback?.RobotGripperState switch
			{
				InstallState.None => "未安装",
				InstallState.BottleGripper => "普通瓶子夹爪",
				InstallState.RotaryGripper => "旋蒸瓶夹爪",
				_ => "未知"
			};

			// 更新任务完成状态文本
			TaskFinishStateText = TaskFeedback?.RobotTaskFinishState switch
			{
				0 => "未完成",
				1 => "成功",
				2 => "失败",
				_ => $"未知状态({(TaskFeedback?.RobotTaskFinishState ?? 0)})"
			};
		}

		/// <summary>
		/// 设备状态变化事件处理
		/// </summary>
		private void OnDeviceStatusChanged(object sender, DeviceStatusEventArgs e)
		{
			if (_disposed)
				return;

			try
			{
				// 仅处理与机器人相关的事件
				if (_deviceManager?.Robot != null && (e.DeviceId == "RobotTask" || e.DeviceId == "RobotDevice"))
				{
					// 在UI线程中更新状态
					App.Current.Dispatcher.Invoke(async () =>
					{
						// 直接调用刷新状态方法
						await RefreshStatus();
					});
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "处理设备状态变化事件失败");
			}
		}
		#endregion

		/// <summary>
		/// 重新初始化
		/// </summary>
		public void Reinitialize()
		{
			try
			{
				_logger?.LogInformation("正在重新初始化RobotControlViewModel");

				// 确保事件处理程序只注册一次
				_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;
				//_deviceStatusService.DeviceStatusChanged += OnDeviceStatusChanged;

				// 重置标记
				if (_disposed)
				{
					_disposed = false;
				}

				// 初始化任务参数
				InitializeTaskParameters();

				// 刷新状态
				_ = RefreshStatus();
			}
			catch (Exception ex)
			{
				_logger?.LogError(ex, "重新初始化RobotControlViewModel失败");
			}
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing)
				{
					// 取消订阅事件
					_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;
					_logger?.LogInformation("已取消订阅设备状态变化事件");

					// 清空引用
					_robotStatus = null;
					_taskFeedback = null;
					_currentTask = null;
				}

				_disposed = true;
			}
		}
	}
}